<template>
  <div ref="dom" class="charts chart-bar"></div>
</template>

<script>
import echarts from 'echarts'
import tdTheme from './theme.json'
import { on, off } from '@/libs/tools'
echarts.registerTheme('tdTheme', tdTheme)
export default {
  name: 'ChartBar',
  props: {
    value: Object,
    text: String,
    subtext: String
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    gengxinshuju() {
      this.$nextTick(() => {
        let xAxisData = Object.keys(this.value)
        let seriesData = Object.values(this.value)
        let option = {
          title: {
            text: this.text,
            subtext: this.subtext,
            x: 'center'
          },
          tooltip:{
            trigger: 'axis',
            formatter: function (params, ticket, callback) {
                const item = params[0];
                return `
                        金额：${item.data} 元</br>
                      `;
            }
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel:{  
              interval: 0 ,
              rotate: -40
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: seriesData,
            type: 'bar'
          }]
        }
        this.dom = echarts.init(this.$refs.dom, 'tdTheme')
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      })
    }
  },
  mounted () {
    this.gengxinshuju()
  },
  watch: {
    'value': function (newVal) {
      this.gengxinshuju()
    }
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
